<template>
  <div>
    <el-dialog
      title="分配角色"
      :visible="showRoleDialog"
      @close="handleCloseDialog"
      @open="handleOpenDialog"
    >
      <el-checkbox-group v-model="checkList" v-loading="loading">
        <el-checkbox v-for="item in rolelist" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button type="primary" size="small" @click="assignRoles">
          确定
        </el-button>
        <el-button size="small" @click="handleCloseDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleListApi } from '@/api/setting'
import { getSysUserInfoApi } from '@/api/user'
import { assignRolesApi } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [], //  数组，存储提交给后台的选中的角色id
      rolelist: [],
      loading: false
    }
  },
  created() {},
  methods: {
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },

    // 打开弹层时，所触发的方法
    async handleOpenDialog() {
      this.loading = true
      // this.getRoleList()
      // this.getEmployeeDetail()
      // 效果：等两个接口请求完了，再关闭loading
      // 1. 等待原则：等待所有的promise都完成，才会继续执行
      //    Promise.all([promise1, promise2]).then((values) => { .... })
      // 2. async函数，默认就相当于进行了一层promise包裹，async函数的执行结果，本身就是一个promise对象
      Promise.all([this.getRoleList(), this.getEmployeeDetail()]).then(() => {
        this.loading = false
      })
    },

    // 获取角色列表
    async getRoleList() {
      const {
        data: { rows }
      } = await getRoleListApi(1, 9999)
      this.rolelist = rows
    },
    // 获取员工详情
    async getEmployeeDetail() {
      const { data } = await getSysUserInfoApi(this.userId)
      this.checkList = data.roleIds
    },

    async assignRoles() {
      await assignRolesApi(this.userId, this.checkList)
      this.$message.success('分配角色成功')
      this.handleCloseDialog()
    }
  }
}
</script>
<style scoped></style>
